// pages/account/account.js
const request = require('../../utils/promise.js')
const baseUtil = require('../../utils/util.js')
const rsaUtil = require('../../utils/rsa_util.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    initFlag: false, // 一开始不显示，初始化完成才显示。避免因为变量值改变，不同页面一闪而过
    msgCount: 0,
    userId: -1,
    username: null,
    score: 0,
    avatarUrl: '',
    iscompleteUser: false,
    completeUser: { // 完善老用户信息
      phoneModal: false, // 发送短信弹框
      isAddUsername: false, // 是否需要添加昵称
      isAddPhone: false, // 是否需要添加手机号
      captchaSrc: '',
      captchaVal: '',
      username: '',
      phone: '',
      smsCode: ''
    },
    isNewUser: false,
    newUser: { // 新用户信息
      isFirstView: true, // 默认显示第一步
      isSecondView: false, // 第二步视图不显示
      phone: '',
      captchaVal: '',
      captchaSrc: '',
      isAddUsername: false, // 是否需要添加昵称
      username: '',
      smsCode: ''
    },
    publicSwitchChecked: false,
    isCancellation: false, // 注销账户结果

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    // 检测是否登录, 未登录再次登录
    if (!wx.getStorageSync('openId')) {
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId，以及基础用户信息
          if (res.code) {
            request.GET("/user/onLogin/code2Session", {
              code: res.code
            }).then(res => {
              console.log('再次登录获取 openId: ', res);
              if (res.data && res.data.success) {
                wx.setStorageSync('userId', res.data.userId); // 缓存用户id，如果第一次注册是id为-1
                wx.setStorageSync('username', res.data.username); // 缓存昵称, 如果第一次注册时为空
                wx.setStorageSync('avatarUrl', res.data.avatarUrl); // 缓存用户头像, 如果第一次注册时默认灰色头像
                wx.setStorageSync('openId', res.data.openId); // 缓存用户
                this.setData({
                  userId: res.data.userId,
                  username: res.data.username,
                  score: res.data.score,
                  avatarUrl: res.data.avatarUrl
                })

                this.initViewShow(res.data.isNewWXUser, res.data.username, res.data.phone);
              }
            })
          }
        }
      })
    } else {
      // 已登录，刷新用户信息
      request.GET('/user/userInfo', {
        openId: wx.getStorageSync('openId')
      }).then(res => {
        let id = -1;
        let username = "";
        let score = 0;
        let avatarUrl = "";
        let phone = "";
        let publicSwitchChecked = false;

        if (res.data.resCode == 200) {
          id = res.data.userInfo['id'];
          username = res.data.userInfo['username'];
          score = res.data.userInfo['score'];
          avatarUrl = res.data.userInfo['avatarUrl'];
          phone = res.data.userInfo['phone'];
          publicSwitchChecked = res.data.userInfo['isPublicStatus']==1?true:false;
        }
        this.setData({
          userId: id,
          username: username,
          score: score,
          avatarUrl: avatarUrl,
          publicSwitchChecked: publicSwitchChecked
        })

        this.initViewShow(res.data.isNewWXUser, username, phone);
      })
    }

    // 获取消息数量
    this.reqUserMessageCount();

    // 再次进入页面，取消显示注销结果
    this.setData({
      isCancellation:false
    });
    
  },
  /**
   * 初始化视图的显示
   */
  initViewShow: function(isNewWXUser, username, phone) {
    if(isNewWXUser){
      // 新用户
      this.setData({
        isNewUser:true,
        iscompleteUser:false, // 是新用户，那么老用户页面不显示
        initFlag: true
      })

      this.getArithmetic('wxNewUser');
    }else{
      // 老用户
      let isAddUsername = false;
      let isAddPhone = false;
      
      // 昵称为空或者不是中文，需要添加
      if (baseUtil.isNotChineseStr(username)) {
        isAddUsername = true;
      }
      // 昵称超过5个字符，就算是中文，也不合格
      if (username.length > 5) {
        isAddUsername = true;
      }

      // 手机号空，需要添加
      if (!phone) {
        isAddPhone = true;
      }

      // 控制老用户，完善信息view显示
      this.setData({
        ['completeUser.isAddPhone']: isAddPhone,
        ['completeUser.isAddUsername']: isAddUsername,
        iscompleteUser: isAddPhone || isAddUsername,
        isNewUser: false, // 是老用户，那么新用户页面不显示
        initFlag: true
      })
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /** 
   * 页面被用户分享时执行 
   */
  onShareAppMessage() {

  },

  /** 
   * 分享到朋友圈 
   */
  onShareTimeline() {

  },

  /**
   * 请求获取通知的消息数量
   */
  reqUserMessageCount() {
    if (wx.getStorageSync('openId')) {
      request.GET('/message/unread/count', {
        openId: wx.getStorageSync('openId')
      }).then(res => {
        // console.log(res);
        if (res.data.resCode == 200) {
          this.setData({
            msgCount: res.data.unreadCount,
          })
        }
      })
    }
  },

  /**
   * 跳转 '我的' 相关页面
   */
  clickViewDataAboutMe(e) {

    let url = '/pages/personal/personal'; // 默认个人中心
    const pagePath = e.currentTarget.dataset.page;
    if (pagePath == 'my_notice') {
      url = '/pages/notice/notice?isRead=0'; // 通知
    } else if (pagePath == 'my_task') {
      url = '/pages/my_task/my_task?userId=' + wx.getStorageSync('userId'); // 我的任务
    } else if (pagePath == 'my_weekly') {
      url = '/pages/weekly/weekly?userId=' + wx.getStorageSync('userId'); // 我的计划
    } else if (pagePath == 'work_signed') {
      url = '/pages/signed/signed'; // 打卡签到
    }

    wx.navigateTo({
      url: url,
    })
  },
  /**
   * 注销用户
   */
  cancellationUser() {
    let that = this;
    wx.showModal({
      title: '注销账户确认',
      content: '注销后，系统会清除账户信息，本账户将无法登录使用，请谨慎操作！请您再次确认是否注销？',
      success(res) {
        if (res.confirm) {
          let ts = baseUtil.getCurTimeSeconds();
          let data = {
            cui:wx.getStorageSync('cui'),
            rui:that.data.userId,
            ts:ts
          }
          let deData = rsaUtil.decryptLong(JSON.stringify(data));
          let sign = rsaUtil.sign(deData);

          request.USER_POST("/user/cancellation",{
            data:deData,
            ds:sign,
            ts:ts
          }).then(res => {
            if (res.statusCode==200) {
              if(res.data.result){

                wx.showToast({
                  title: res.data.message,
                  icon: 'success',
                  duration: 1500,
                  mask: true
                })

                // 清除主要的缓存
                wx.removeStorageSync('userId');
                wx.removeStorageSync('openId');
                wx.removeStorageSync('username');
                wx.removeStorageSync('avatarUrl');

                // 显示注销结果
                that.setData({
                  isCancellation:true
                });

              }else{
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 1500,
                  mask: true
                })
              }
            } else {
              wx.showToast({
                title: '注销账户异常',
                icon: 'none',
                duration: 1500,
                mask: true
              })
            }
          })

        }
      }
    });

  },
  /**
   * 点击完善用户信息
   */
  clickCompleteUserInfo() {
    // 昵称部分校验
    let isAddUsername = this.data.completeUser.isAddUsername;
    if(isAddUsername){
      let usernameVal = this.data.completeUser.username.trim();
      if (usernameVal.length == 0) {
        wx.showToast({
          title: '请输入昵称',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      } else {
        if (baseUtil.isNotChineseStr(usernameVal)) {
          wx.showToast({
            title: '昵称只能是中文',
            icon: 'none',
            duration: 1500,
            mask: true
          })
          return;
        }
      }
    }

    // 手机号部分校验
    let isAddPhone = this.data.completeUser.isAddPhone;
    if(isAddPhone){
      let phoneVal = this.data.completeUser.phone.trim();
      if(phoneVal==''){
        wx.showToast({
          title: '请输入手机号',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      }else if(!baseUtil.isChinaCellPhoneNumber(phoneVal)){
        wx.showToast({
          title: '手机号无效',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      }

      let smsCodeVal = this.data.completeUser.smsCode.trim();
      if(smsCodeVal.length==0){
        wx.showToast({
          title: '请输入短信验证码',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      }else if(!baseUtil.isSmsCode(smsCodeVal)){
        wx.showToast({
          title: '短信验证码无效',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      }
    }
    
    // 验证通过之后，开始完善老用户信息
    let param = {
      openId:wx.getStorageSync('openId'),
      username:this.data.completeUser.username.trim(),
      phone:this.data.completeUser.phone.trim(),
      smsCode:this.data.completeUser.smsCode.trim()
    }
    request.GET('/user/completeUserInfo', param).then(result => {
      if (result.data.resCode == 200) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })

        this.setData({
          userId: result.data.userInfo['id'],
          username: result.data.userInfo['username'],
          score: result.data.userInfo['score'],
          avatarUrl: result.data.userInfo['avatarUrl']
        })
        // 缓存昵称、用户id、用户头像
        wx.setStorageSync('userId', result.data.userInfo['id']);
        wx.setStorageSync('username', result.data.userInfo['username']);
        wx.setStorageSync('avatarUrl', result.data.userInfo['avatarUrl']);
        // 获取消息数量
        this.reqUserMessageCount();

        // 隐藏老用户的相关输入视图
        this.setData({
          ['completeUser.isAddUsername']: false,
          ['completeUser.isAddPhone']: false,
          iscompleteUser: false
        })

      } else if(result.data.resCode == 201){
        wx.showToast({
          title: result.data.message,
          icon: 'none',
          duration: 1500,
          mask: true
        })
      } else {
        wx.showToast({
          title: '提交异常',
          icon: 'error',
          duration: 1500,
          mask: true
        })
      }

    })
    
  },
  bindUsernameInput(e) {
    this.setData({
      ['completeUser.username']: e.detail.value
    })
  },
  bindPhoneInput(e) {
    this.setData({
      ['completeUser.phone']: e.detail.value
    })
  },
  bindSmsCodeInput(e) {
    this.setData({
      ['completeUser.smsCode']: e.detail.value
    })
  },
  /**
   * 获取图形验证码
   */
  getArithmetic(apiType){
    let ts = baseUtil.getCurTimeSeconds();
    let data = {
      cui:wx.getStorageSync('cui'),
      apiType:apiType,
      ts:ts
    }
    let deData = rsaUtil.decryptLong(JSON.stringify(data));
    let sign = rsaUtil.sign(deData);

    let that = this;
    request.USER_POST("/captcha/getArithmetic",{
      data: deData,
      ds: sign,
      ts: ts
    }).then(res => {
      if (res.statusCode==200 && res.data.result) {
        wx.hideLoading();

        // 老用户完善
        if(apiType=='wxCompleteUser'){
          that.setData({
            ['completeUser.captchaSrc']: res.data.data,
            ['completeUser.captchaVal']: '',
            ['completeUser.phoneModal']: true
          })
        }

        // 新用户
        if(apiType=='wxNewUser'){
          that.setData({
            ['newUser.captchaSrc']: res.data.data,
            ['newUser.captchaVal']: ''
          })
        }
        
      } else {
        wx.showToast({
          title: '图形验证码获取异常',
          icon: 'none',
          duration: 1500,
          mask: true
        })
      }
    })
  },
  clickShowPhoneModal() {
    let val = this.data.completeUser.phone.trim();
    if(val==''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }else if(!baseUtil.isChinaCellPhoneNumber(val)){
      wx.showToast({
        title: '手机号无效',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }else{
      this.getArithmetic('wxCompleteUser');
    }
  },
  clickHidePhoneModal() {
    this.setData({
      ['completeUser.phoneModal']: false
    })
  },
  clickRefreshCodeCompleteUser(){
    this.getArithmetic('wxCompleteUser');
  },
  bindCaptchaValInput(e) {
    this.setData({
      ['completeUser.captchaVal']: e.detail.value
    })
  },
  clickSendSmsCompleteUser() {
    let val = this.data.completeUser.captchaVal.trim();
    if(val == '') {
      wx.showToast({
        title: '请输入计算结果',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }else if(!baseUtil.isCaptchaResult(val)){
      wx.showToast({
        title: '计算结果无效',
        icon: 'none',
        duration: 1500,
        mask: true
      })
    }else{
      // 校验通过，开始发送短信
      let ts = baseUtil.getCurTimeSeconds();
      let pn = this.data.completeUser.phone.trim();

      let data = {
        cui:wx.getStorageSync('cui'),
        apiType:'wxCompleteUser',
        pn:pn,
        vc:val,
        ts:ts
      }

      let deData = rsaUtil.decryptLong(JSON.stringify(data));
      let sign = rsaUtil.sign(deData);

      let that = this;
      request.USER_POST("/aliyun/sendSms",{
        data:deData,
        ds:sign,
        ts:ts
      }).then(res => {
        if (res.statusCode==200) {
          if(res.data.result){
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 1000,
              mask: true
            })
  
            that.setData({
              ['completeUser.phoneModal']: false
            })
          }else{
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 1500,
              mask: true
            })
           
            // 发送失败，自动刷新图形码
            setTimeout(function () {
              that.getArithmetic('wxCompleteUser');
            }, 1500)
          }
        } else {
          wx.showToast({
            title: '发送失败',
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      })

    }
  },


  bindPhoneInput2(e) {
    this.setData({
      ['newUser.phone']: e.detail.value
    })
  },
  bindCaptchaValInput2(e) {
    this.setData({
      ['newUser.captchaVal']: e.detail.value
    })
  },
  bindUsernameInput2(e) {
    this.setData({
      ['newUser.username']: e.detail.value
    })
  },
  bindSmsCodeInput2(e) {
    this.setData({
      ['newUser.smsCode']: e.detail.value
    })
  },
  clickRefreshCodeNewUser(){
    this.getArithmetic('wxNewUser');
  },
  clickSendSmsNewUser(){
    let phoneVal = this.data.newUser.phone.trim();
    if(phoneVal==''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }else if(!baseUtil.isChinaCellPhoneNumber(phoneVal)){
      wx.showToast({
        title: '手机号无效',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }

    let captchaVal = this.data.newUser.captchaVal.trim();
    if(captchaVal == '') {
      wx.showToast({
        title: '请输入计算结果',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }else if(!baseUtil.isCaptchaResult(captchaVal)){
      wx.showToast({
        title: '计算结果无效',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }

    // 校验通过，开始发送短信
    let ts = baseUtil.getCurTimeSeconds();
    let data = {
      cui:wx.getStorageSync('cui'),
      apiType:'wxNewUser',
      pn:phoneVal,
      vc:captchaVal,
      ts:ts
    }
    let deData = rsaUtil.decryptLong(JSON.stringify(data));
    let sign = rsaUtil.sign(deData);

    let that = this;
    request.USER_POST("/aliyun/sendSms",{
      data:deData,
      ds:sign,
      ts:ts
    }).then(res => {
      if (res.statusCode==200) {
        if(res.data.result){
          // 发送成功后嵌套查询手机号是否已存在
          request.GET('/user/isUserExists', {phone:phoneVal}).then(result => {
            if (result.data.resCode == 200) {
              wx.showToast({
                title: '发送成功',
                icon: 'success',
                duration: 1000,
                mask: true
              })

              // 进入第二步
              that.setData({
                ['newUser.isAddUsername']: !result.data.isExists,
                ['newUser.isFirstView']: false,
                ['newUser.isSecondView']: true
              })

            } else {
              wx.showToast({
                title: '数据异常',
                icon: 'error',
                duration: 1500,
                mask: true
              })
            }
          })
        }else{
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1500,
            mask: true
          })

          // 发送短信失败，需要刷新验证码
          let that = this;
          setTimeout(function () {
            that.getArithmetic('wxNewUser');
          }, 1500)
        }
      } else {
        wx.showToast({
          title: '发送失败',
          icon: 'none',
          duration: 1500,
          mask: true
        })
      }
    })

  },
  /**
   * 微信新用户
   */
  clickNewUserInfo() {
    let phoneVal = this.data.newUser.phone.trim();
    let usernameVal = this.data.newUser.username.trim();
    let smsCodeVal = this.data.newUser.smsCode.trim();

    // 步骤二，手机号再次校验
    if(phoneVal==''){
      wx.showToast({
        title: '请先输入手机号',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }else if(!baseUtil.isChinaCellPhoneNumber(phoneVal)){
      wx.showToast({
        title: '请先输入有效的手机号',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }

    // 昵称部分校验
    let isAddUsername = this.data.newUser.isAddUsername;
    if(isAddUsername){
      if (usernameVal.length == 0) {
        wx.showToast({
          title: '请输入昵称',
          icon: 'none',
          duration: 1500,
          mask: true
        })
        return;
      } else {
        if (baseUtil.isNotChineseStr(usernameVal)) {
          wx.showToast({
            title: '昵称只能是中文',
            icon: 'none',
            duration: 1500,
            mask: true
          })
          return;
        }
      }
    }

    // 短信验证码校验
    if(smsCodeVal.length==0){
      wx.showToast({
        title: '请输入短信验证码',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }else if(!baseUtil.isSmsCode(smsCodeVal)){
      wx.showToast({
        title: '短信验证码无效',
        icon: 'none',
        duration: 1500,
        mask: true
      })
      return;
    }
    
    // 验证通过之后，新用户注册
    let param = {
      openId:wx.getStorageSync('openId'),
      username:usernameVal,
      phone:phoneVal,
      smsCode:smsCodeVal
    }
    request.GET('/user/newUserInfo', param).then(result => {
      if (result.data.resCode == 200) {
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000,
          mask: true
        })

        this.setData({
          userId: result.data.userInfo['id'],
          username: result.data.userInfo['username'],
          score: result.data.userInfo['score'],
          avatarUrl: result.data.userInfo['avatarUrl']
        })
        // 缓存昵称、用户id、用户头像
        wx.setStorageSync('userId', result.data.userInfo['id']);
        wx.setStorageSync('username', result.data.userInfo['username']);
        wx.setStorageSync('avatarUrl', result.data.userInfo['avatarUrl']);
        // 获取消息数量
        this.reqUserMessageCount();

        // 隐藏新增用户视图
        this.setData({
          ['newUser.isFirstView']: true,
          ['newUser.isSecondView']: false,
          ['newUser.isAddUsername']: false,
          isNewUser: false
        })

      } else if(result.data.resCode == 201){
        wx.showToast({
          title: result.data.message,
          icon: 'none',
          duration: 1500,
          mask: true
        })
      } else {
        wx.showToast({
          title: '提交异常',
          icon: 'error',
          duration: 1500,
          mask: true
        })
      }
    })
    
  },

  /**
   * 修改公开个人信息
   */
  publicSwitchChange(e) {
    this.setData({
      publicSwitchChecked:e.detail.value
    })

    let param = {
      userId:this.data.userId,
      publicSwitchChecked:this.data.publicSwitchChecked,
    }
    request.GET('/user/publicSwitchChange', param).then(result => {
      if (result.data.resCode != 200) {
        wx.showToast({
          title: '修改异常',
          icon: 'error',
          duration: 1500,
          mask: true
        })
      }
    })
  },
  cancelLogin() {
    // 点击行为触发，退出小程序
    wx.exitMiniProgram();
  }

})